<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <title>设备地图监控</title>
  <style>
    #container {
      width: 100%;
      height: 100vh;
    }

    /* 弹出层样式 */
    #popup {
      position: absolute;
      top: 20px;
      left: 20px;
      background-color: #ffffff;
      border: 1px solid #e6e6e6;
      border-radius: 6px;
      padding: 15px 20px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      z-index: 9999;
      display: none;
      max-width: 300px;
      min-width: 200px;
      box-sizing: border-box;
    }

    #popup .info {
      margin-bottom: 12px;
      line-height: 1.6;
      font-size: 14px;
    }

    #popup .info strong {
      color: #555;
      font-weight: 600;
    }

    #popup .info span {
      color: #666;
    }

    #popup .info #popup-onlineStatus.online {
      color: #09bb07;
    }

    #popup .info #popup-onlineStatus.offline {
      color: #f56c6c;
    }

    #popup .button-group {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      margin-top: 15px;
    }

    #popup button {
      padding: 8px 15px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.2s ease-in-out;
    }

    #popup button:first-of-type {
      background-color: #409eff;
      color: white;
    }

    #popup button:first-of-type:hover {
      background-color: #66b1ff;
    }

    #popup button:last-of-type {
      background-color: #f5f5f5;
      color: #606266;
      border: 1px solid #dcdfe6;
    }

    #popup button:last-of-type:hover {
      background-color: #ebeef5;
      color: #409eff;
      border-color: #c6e2ff;
    }

    /* 闪烁动画 */
    @keyframes flashScale {
      0% { transform: scale(1); }
      50% { transform: scale(1.4); }
      100% { transform: scale(1); }
    }
  </style>
</head>
<body>
<div id="container"></div>

<!-- 弹窗 -->
<div id="popup">
  <div class="info">
    <strong>经纬度：</strong><span id="popup-coords"></span>
  </div>
  <div class="info">
    <strong>设备名称：</strong><span id="popup-deviceName"></span>
  </div>
  <div class="info">
    <strong>设备编号：</strong><span id="popup-deviceId"></span>
  </div>
  <div class="info">
    <strong>在线状态：</strong><span id="popup-onlineStatus"></span>
  </div>
  <div class="info">
    <strong>地址：</strong><span id="popup-address"></span>
  </div>
  <div class="button-group">
    <button onclick="handleDetail()">查看详情</button>
    <button onclick="hidePopup()">关闭</button>
  </div>
</div>

<!-- JS 资源 -->
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/js/websocket-device.js}"></script>
<script src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>

<script th:inline="javascript">
  var ctx = [[@{/}]];
</script>

<script>
  // ========================
  // 地图初始化
  // ========================
  window.onload = function () {
    console.log("页面加载完成");
    const map = new TMap.Map("container", {
      center: new TMap.LatLng(27.8333, 113.1333),
      zoom: 15,
    });

    // === 存储映射关系 ===
    const deviceMarkerMap = {}; // devNumber -> markerId
    const deviceDataMap = {};   // devNumber -> 完整设备数据

    $.post(ctx + "deviceManager/device/list", {}, function (res) {
      const devices = res.rows || [];
      const geometries = [];

      devices
              .filter(d => d.latitude && d.longitude)
              .forEach(device => {
                const markerId = "device-" + device.devId;
                // 保存映射
                deviceMarkerMap[device.devNumber] = markerId;
                deviceDataMap[device.devNumber] = { ...device }; // 深拷贝一份


                geometries.push({
                  id: markerId,
                  styleId: (device.status == 1 || device.status === '1') ? "online" : "offline",
                  //styleId : "offline",
                  position: new TMap.LatLng(device.latitude, device.longitude),
                  properties: { device },
                });
              });

      const markerLayer = new TMap.MultiMarker({
        map: map,
        styles: {
          online: new TMap.MarkerStyle({
            width: 32,
            height: 48,
            anchor: { x: 16, y: 48 },
            src: ctx + "img/map-marker-online.png",
          }),
          offline: new TMap.MarkerStyle({
            width: 32,
            height: 48,
            anchor: { x: 16, y: 48 },
            src: ctx + "img/map-marker-offline.png",
          }),
        },
        geometries: geometries,
      });

      // 暴露到全局
      window.deviceMarkerLayer = markerLayer;
      window.deviceMarkerMap = deviceMarkerMap;
      window.deviceDataMap = deviceDataMap;

      // 点击事件
      markerLayer.on("click", function (evt) {
        const device = evt.geometry.properties.device;
        const pos = evt.geometry.position;
        const popup = document.getElementById("popup");


        console.log(device,'eeeeeeeeeeeeeeeeeeeeeeee',device.status == 1 || device.status === '1')

        if (popup) {
          document.getElementById("popup-coords").textContent = `${pos.lat.toFixed(5)}, ${pos.lng.toFixed(5)}`;
          document.getElementById("popup-address").textContent = device.currentLocation || "未知位置";
          document.getElementById("popup-deviceName").textContent = device.devName || "未知名称";
          document.getElementById("popup-deviceId").textContent = device.devNumber || "未知编号";

          const statusEl = document.getElementById("popup-onlineStatus");
          if (statusEl) {
            statusEl.textContent = (device.status == 1 || device.status === '1') ? "在线" : "离线";
            statusEl.className = (device.status == 1 || device.status === '1') ? "online" : "offline";
          }
          popup.style.display = "block";
        }
      });
    });
  };

  // ========================
  // WebSocket 实时更新 + 闪烁动画
  // ========================
  WebSocketDevice.addListener(function (msg) {
    if (!msg?.devNumber || msg.status === undefined) return;

    const devNumber = msg.devNumber;
    const isOnline = Boolean(msg.status);
    const device = window.deviceDataMap?.[devNumber];

    if (!device) {
      console.debug(`设备 ${devNumber} 未在地图中`);
      return;
    }

    const markerLayer = window.deviceMarkerLayer;
    const markerId = window.deviceMarkerMap?.[devNumber];
    if (!markerLayer || !markerId) return;

    // 获取当前状态（判断是否是“上线”动作）
    const geo = markerLayer.getGeometries().find(g => g.id === markerId);
    const wasOffline = geo?.styleId === "offline";

    // 更新完整 geometry（⚠️ 必须包含 position 才不会消失！）
    markerLayer.updateGeometries([{
      id: markerId,
      styleId: isOnline ? "online" : "offline",
      position: new TMap.LatLng(device.latitude, device.longitude),
      properties: {
        device: { ...device, status: isOnline ? '1' : '0' }
      }
    }]);

    // 更新内存状态
    device.status = isOnline ? '1' : '0';

    console.log(`✅ 已更新设备 [${devNumber}] 为 ${isOnline ? '在线' : '离线'}`);

    // 只有从离线变在线才触发闪烁
    if (wasOffline && isOnline) {
      triggerFlashAnimation(markerId);
    }

    // 同步弹窗（如果正显示该设备）
    const popup = document.getElementById("popup");
    const currentDevIdEl = document.getElementById("popup-deviceId");
    if (popup && popup.style.display !== "none" && currentDevIdEl?.textContent.trim() === devNumber) {
      const statusEl = document.getElementById("popup-onlineStatus");
      statusEl.textContent = isOnline ? "在线" : "离线";
      statusEl.className = isOnline ? "online" : "offline";
    }
  });

  // ========================
  // 闪烁动画函数
  // ========================
  function triggerFlashAnimation(markerId) {
    const markerLayer = window.deviceMarkerLayer;
    const geo = markerLayer.getGeometries().find(g => g.id === markerId);
    if (!geo) return;

    const originalWidth = 32, originalHeight = 48;
    const bigWidth = 46, bigHeight = 68;

    // 放大 → 缩小 → 放大 → 缩小（两闪）
    [
      [bigWidth, bigHeight],
      [originalWidth, originalHeight],
      [bigWidth, bigHeight],
      [originalWidth, originalHeight]
    ].forEach((size, i) => {
      setTimeout(() => {
        markerLayer.updateGeometries([{
          id: markerId,
          styleId: geo.styleId,
          position: geo.position,
          width: size[0],
          height: size[1],
          properties: geo.properties
        }]);
      }, i * 300);
    });
  }

  // ========================
  // 弹窗操作
  // ========================
  function handleDetail() {
    alert("你点击了【查看详情】");
  }

  function hidePopup() {
    const popup = document.getElementById("popup");
    if (popup) popup.style.display = "none";
  }
</script>
</body>
</html>